import { useDeleteMessage, useFeedback } from '@/hooks/chat-hooks';
import { useSetModalState } from '@/hooks/common-hooks';
import { IRemoveMessageById, useSpeechWithSse } from '@/hooks/logic-hooks';
import { IFeedbackRequestBody } from '@/interfaces/request/chat';
import { hexStringToUint8Array } from '@/utils/common-util';
import { SpeechPlayer } from 'openai-speech-stream-player';
import { useCallback, useEffect, useRef, useState } from 'react';
import { message } from 'antd';
// import { PauseCircleOutlined, SoundOutlined } from '@ant-design/icons';

export const useSendFeedback = (messageId: string) => {
  const { visible, hideModal, showModal } = useSetModalState();
  const { feedback, loading } = useFeedback();

  const onFeedbackOk = useCallback(
    async (params: IFeedbackRequestBody) => {
      const ret = await feedback({
        ...params,
        messageId: messageId,
      });

      if (ret === 0) {
        hideModal();
      }
    },
    [feedback, hideModal, messageId],
  );

  return {
    loading,
    onFeedbackOk,
    visible,
    hideModal,
    showModal,
  };
};

export const useRemoveMessage = (
  messageId: string,
  removeMessageById?: IRemoveMessageById['removeMessageById'],
) => {
  const { deleteMessage, loading } = useDeleteMessage();

  const onRemoveMessage = useCallback(async () => {
    if (messageId) {
      const code = await deleteMessage(messageId);
      if (code === 0) {
        removeMessageById?.(messageId);
      }
    }
  }, [deleteMessage, messageId, removeMessageById]);

  return { onRemoveMessage, loading };
};

export const useSpeech = (content: string, audioBinary?: string) => {
  const ref = useRef<HTMLAudioElement>(null);
  const { read } = useSpeechWithSse();
  const player = useRef<SpeechPlayer>();
  const [isPlaying, setIsPlaying] = useState<boolean>(false);
  const [isLoading, setIsLoading] = useState<boolean>(false);

  const initialize = useCallback(async () => {
    try {
      player.current = new SpeechPlayer({
        audio: ref.current!,
        onPlaying: () => {
          setIsPlaying(true);
        },
        onPause: () => {
          setIsPlaying(false);
        },
        onChunkEnd: () => {},
        mimeType: MediaSource.isTypeSupported('audio/mpeg')
          ? 'audio/mpeg'
          : 'audio/mp4; codecs="mp4a.40.2"',
      });
      await player.current.init();
    } catch (error) {
      console.error('Failed to initialize speech player:', error);
      message.error('语音播放器初始化失败');
    }
  }, []);

  const pause = useCallback(() => {
    player.current?.pause();
  }, []);

  const speech = useCallback(async () => {
    if (!content) {
      message.warning('没有可播放的内容');
      return;
    }

    try {
      setIsLoading(true);
      // 清理内容中的特殊字符
      const newContent = content.replaceAll('\n', '').replaceAll('#', '').replaceAll('*', '');
      const response = await read({ text: newContent });
      
      if (!response) {
        message.error('获取语音数据失败');
        setIsPlaying(false);
        return;
      }

      player?.current?.feedWithResponse(response);
    } catch (error) {
      console.error('Speech playback error:', error);
      message.error('语音播放失败');
      setIsPlaying(false);
    } finally {
      setIsLoading(false);
    }
  }, [read, content]);

  const handleRead = useCallback(async () => {
    if (isPlaying) {
      setIsPlaying(false);
      pause();
    } else {
      setIsPlaying(true);
      await speech();
    }
  }, [setIsPlaying, speech, isPlaying, pause]);

  useEffect(() => {
    if (audioBinary) {
      try {
        const units = hexStringToUint8Array(audioBinary);
        if (units) {
          player.current?.feed(units);
        }
      } catch (error) {
        console.error('Failed to process audio binary:', error);
        message.error('音频数据处理失败');
      }
    }
  }, [audioBinary]);

  useEffect(() => {
    initialize();
    // 清理函数
    return () => {
      player.current?.pause();
      player.current = undefined;
    };
  }, [initialize]);

  return { ref, handleRead, isPlaying, isLoading };
};
